<template>
  <div class="msgContainer">
    <!-- msgList 消息数组-->
    <div class="msgContent" id="msgShow">
      <div v-for="(item,index) in msgList" :key="index" class="msgList">
        <!-- 对方 -->
        <div class="msg-others" v-if=!myMsg(item.uid)>
          <img src="../assets/logo.png" alt="">
          <div class="info-others">
            <p class="time-others">{{item.email}}  {{msgTime(item.timestamp)}}</p>
            <div class="info-content-others">{{item.text}}</div>
          </div>
        </div>
        <!-- 我的 -->
        <div class="msg-mine" v-else>
          <div class="info-mine">
            <p class="time-mine">{{item.email}}  {{msgTime(item.timestamp)}}</p>
            <div class="info-content-mine">{{item.text}}</div>
          </div>
          <img src="../assets/logo.png" alt="">
        </div>
      </div>
    </div>
    <div class="msgBox">
      <textarea class="msgArea" v-model="msg" @keydown.shift.enter="newliner" @keydown="sender"></textarea>
      <p id="iid">当前面试号：{{this.currentInviteId}}</p>
      <button @click="onSubmit">发送(Enter)</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "TalkBox",
  data() {
    return {
      msgList: [],
      msg: "",
      currentInvite: {},
      currentInviteId: "",
      ws: {},
      shiftEnter: false
    }
  },

  created() {
    //this.startServerWS();
    //setTimeout(this.getWS, 10000);
    //this.wsSend("hello", 1000);
    this.currentInvite = JSON.parse(window.sessionStorage.getItem("interview"));
    if (!this.currentInvite) {
      this.$message.info("未接受邀请");
    } else {
      this.currentInviteId = this.currentInvite.inviteId;
      window.timer = setInterval(() => {
        setTimeout(this.getMsg, 0)
      }, 1000);
    }
  },
  beforeDestroy() {
    clearInterval(window.timer);
  },
  methods: {
    msgTime(timestamp) {
      function addDateZero(num) {
        return (num < 10 ? "0" + num : num);
      }
      let d = new Date(timestamp);
      return d.getFullYear() + '-' + addDateZero(d.getMonth() + 1) + '-' + addDateZero(d.getDate()) + ' ' + addDateZero(d.getHours()) + ':' + addDateZero(d.getMinutes()) + ':' + addDateZero(d.getSeconds());
    },
    myMsg(uid) {
      return uid === window.sessionStorage.getItem("userId");
    },
    wsSend(msg, retryInterval) {
      if (this.ws.readyState === 1)
        this.ws.send(msg);
      else {
        const ref = this;
        setTimeout(function () {
          ref.wsSend(msg, retryInterval);
        }, retryInterval);
      }
    },
    /**
    startServerWS() {
      /**
       //开启服务器
       const InspireCloud = require("@byteinspire/js-sdk");
       const myServiceId = "qcqsjd";
       const fnName = "websocket_server";

       // 创建轻服务实例
       const inspirecloud = new InspireCloud({
        serviceId: myServiceId,
      });
       // 调用轻服务函数
       inspirecloud
       .run(fnName, {
          token: window.sessionStorage.getItem("token"),
          inviteId: this.currentInvite.inviteId
        })
       .then((data) => {
          console.log(data);
        })
       .catch((error) => {
          this.$message.error(error);
        });
      let vm = require('nodejs-websocket');
      const port = 8082;
      console.log(vm);
      const server = vm.createServer(function (conn) {
        //收到连接请求触发
        conn.on("text", function (str) {
          //收到消息触发接收
          console.log("received: " + str);
          broadcast(str); //广播消息
        })
        conn.on("open", function () {
          //打开连接触发
          console.log("connection opened");
        })
        conn.on("close", function () {
          //断开连接触发
          console.log("connection closed");
        })
        conn.on("error", function (err) {
          //出错触发
          console.log("error: " + err);
        })

        function broadcast(str) {  //广播
          //server.connections 保存每个连接进来的用户
          server.connections.forEach(function (conn) {
            conn.sendText(str)
          })
        }
      }).listen(port);
      console.log(server);
    },
    getWS() {
      this.ws = new WebSocket("wss://qcqsjd.fn.thelarkcloud.com:443/");
      console.log(this.ws)
      this.ws.onopen = function() {
        console.log("websocket open");
      }
      this.ws.onclose = function() {
        console.log("websocket close");
      }
      this.ws.onmessage = function(e) {
        console.log(e.data);
      }
    },
    **/
    getMsg() {
      const InspireCloud = require("@byteinspire/js-sdk");
      const myServiceId = "qcqsjd";
      const fnName = "msg_require";

      // 创建轻服务实例
      const inspirecloud = new InspireCloud({
        serviceId: myServiceId,
      });
      // 调用轻服务函数
      inspirecloud
        .run(fnName, {
          token: window.sessionStorage.getItem("token"),
          inviteId: this.currentInvite.inviteId
        })
        .then((data) => {
          if (data.status === 1){
            this.$message.info(data.message);
            clearInterval(window.timer);
          }
          else
            this.msgList = data;
        })
        .catch((error) => {
          this.$message.error(error);
        });
    },
    sendMsg() {
      const InspireCloud = require("@byteinspire/js-sdk");
      const myServiceId = "qcqsjd";
      const fnName = "msg_save";

      // 创建轻服务实例
      const inspirecloud = new InspireCloud({
        serviceId: myServiceId,
      });
      // 调用轻服务函数
      inspirecloud
        .run(fnName, {
          token: window.sessionStorage.getItem("token"),
          inviteId: this.currentInvite.inviteId,
          text: this.msg
        })
        .then((data) => {
          if (data.status === 1 || 2) {
            this.$message.info(data.message);
            if (data.status === 1)
              clearInterval(window.timer);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        });
    },
    onSubmit() {
      if (!this.currentInvite) {
        this.$message.info("未接受邀请");
      } else {
        this.sendMsg();
        this.msg = "";
      }
    },
    sender(event) {
      if (event.keyCode === 13 && !this.shiftEnter) {
        this.onSubmit();
        event.preventDefault();
      } else if (event.keyCode === 13){
        this.shiftEnter = false;
        event.preventDefault();
      }
    },
    newliner() {
      this.shiftEnter = true;
      this.msg += '\n';
    }
  },
  watch: {
    msgList: {
      handler(newList, oldList) {
        //check identification of two arrays
        if (JSON.stringify(newList) !== JSON.stringify(oldList)) {
          this.$nextTick(function () {
            //scrollToBottom()
            const div = document.getElementById("msgShow");
            if (div)
              div.scrollTop = div.scrollHeight;
          })
        }
      },
      immediate: true
    }
  }
}
</script>

<style lang="less" scoped>
.msgList {
  width: 95%;
  padding: 10px;
}
img{
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.msg-others {
  display: flex;
}
.info-others {
  margin-left: 10px;
}
.time-others{
  font-size: 12px;
  color: rgba(51,51,51,0.8);
  height: 20px;
  line-height: 20px;
  margin: -5px 0 0;
}
.info-content-others{
  max-width: 70%;
  padding: 10px;
  font-size: 14px;
  float: left;
  position: relative;
  margin-top: 8px;
  background: #A3C3F6;
  text-align: left;
  white-space: pre-wrap;
}
.msg-mine {
  display: flex;
  justify-content: flex-end;
}
.info-mine {
  margin-left: 10px;
  text-align: right;
}
.time-mine {
  font-size: 12px;
  color: rgba(51,51,51,0.8);
  height: 20px;
  line-height: 20px;
  margin: -5px 10px 0 0;
}
.info-content-mine {
  max-width: 70%;
  padding: 10px;
  font-size: 14px;
  float: right;
  margin-right: 10px;
  position: relative;
  margin-top: 8px;
  background: #BDFCC9;
  text-align: left;
  white-space: pre-wrap;
}
.msgContainer {
  height: 800px;
}
.msgContent {
  position: relative;
  top: 10px;
  width: 100%;
  height: 88%;
  overflow-y: scroll;
}
.msgBox {
  position: absolute;
  bottom: 5px;
  width: 95%;
  height: 15%;
}
.msgArea {
  position: relative;
  width: 100%;
  height: 70%;
}
button {
  float: right;
  width: 150px;
  height: 20%;
  border-width: 0;
  border-radius: 3px;
  background: #BEBEBE;
  cursor: pointer;
  outline: none;
  font-size: 15px;
}
button:hover {
  background: #BDFCC9;
}
#iid {
  float: left;
}
</style>
